<?php

namespace app\api\controller;

use addons\wanlshop\library\WanlPay\WanlPay;
use addons\wanlshop\library\WanlSdk\Common;
use app\admin\model\wanlshop\Category2;
use app\api\model\wanlshop\GoodsSku;
use app\api\model\wanlshop\GoodsSpu;
use app\api\model\wanlshop\Shop;
use app\common\controller\Api;
use app\common\library\AlibabaSignatureGenerator;
use app\common\library\Baishi;
use app\common\library\HttpClient;
use app\common\library\Qpay;
use app\common\library\RussianPay;
use app\common\library\SfdPay;
use app\common\library\Youdao;
use app\index\model\wanlshop\Pay;
use app\index\model\wanlshop\ShopMarginOrder;
use Client;
use Ip2Region;
use KyTraceQueryReq;
use SimpleXMLElement;
use think\Db;
use think\Exception;
use think\Log;
use function EasyWeChat\Kernel\Support\get_client_ip;
/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    /**
     * 首页
     *
     */
    public function index()
    {
//        $ossUrl = 'https://happygoma.oss-cn-hongkong.aliyuncs.com/uploads/你是我的解药.mp4'; // 替换为您的输入MP4文件路径
//        $outputDir = './directory'; // 替换为您希望输出m3u8和ts文件的目录
//        $success =$this->convertRemoteMp4ToM3u8($ossUrl, $outputDir, 10);// 每片10秒
//        dump($success);exit();

//        $qpay = new Qpay();
//        $data['object_type'] = 'INVOICE';
////        $data['object_id'] = '523661890561253';
////        $data['object_id'] = '48282a53-b50e-4efd-8c50-887e7cad02ec';
//        //c323d2e9-987b-4a18-850f-52562381adff
//        $orderId =  '471194697174520';
//        $res = $qpay->payment($orderId);
//        if($res['status'] == 200){
//            $body = $res['body'];
//            if($body['payment_status'] == 'PAID'){
//                $wanlpay = new WanlPay('qpay');
//               $res = $wanlpay->notify(['out_trade_no'=>$body['object_id'],'transaction_id'=>$body['payment_id']]);
//               dump($res);
//            }
//        }
exit();
        $this->success('请求成功');
    }

  public  function signature($time){
        $user = 'happygomall@163.com';
        $ukey = 'LqaE3RBZvYd3jARa';
        return sha1($user.$ukey.$time);//公共参数，请求公钥
    }

    public  function LR($str_left,$str_right,$length){
        if( empty($str_left) || empty($str_right) || empty($length) ) return '请输入正确的参数';
        $kw = '';
        $str_left_lenght = strlen(iconv("UTF-8", "GBK//IGNORE", $str_left));
        $str_right_lenght = strlen(iconv("UTF-8", "GBK//IGNORE", $str_right));
        $k = $length - ($str_left_lenght+$str_right_lenght);
        for($q=0;$q<$k;$q++){
            $kw .= ' ';
        }
        return $str_left.$kw.$str_right;
    }

    public function fee()
    {

        $glist = array(
            'orderid'=>'订单编号：'.time(),
            'remark'=>'订单备注：备注',
            'name'=>'姓名：小毛',
            'tel'=>'电话：15890956946',
            'z_number'=>'地址：乌兰巴托',
            'goods'=>array(
                '0'=>array('title'=>'裤子','price'=>'100.4','num'=>'10'),
                '1'=>array('title'=>'鞋子','price'=>'20.4','num'=>'10'),
                '2'=>array('title'=>'袜子','price'=>'100','num'=>'10')
            ),
        );
        $content = '';
        $num = count($glist['goods']);
        $i = 1;
        $bianhao  = "订单编号：".time();
        $name  = "小毛";
        $tel  = "15890956946";
        $z_number  = "乌兰巴托";
        $zongprice  = "100";
        $price  = "100";
        $content = '<TEXT x="9" y="10" font="12" w="1" h="2" r="0">'.$bianhao.'
                    <TEXT x="9" y="180" font="12" w="1" h="1" r="0">张三先生       13800138000</TEXT>
                    <TEXT x="9" y="180" font="12" w="1" h="1" r="0">地区       乌兰巴托</TEXT>
                     <TEXT x="9" y="180" font="12" w="1" h="1" r="0">总金额       300</TEXT>
                    </TEXT><TEXT x="80" y="80" font="12" w="2" h="2" r="0">袜子    100 x 1</TEXT>
                    </TEXT><TEXT x="80" y="80" font="12" w="2" h="2" r="0">鞋子    200 x 2</TEXT>';


        $time = time();         //请求时间
        $msgInfo = array(
            'user' => 'happygomall@163.com',
            'stime' => $time,
            'sig' => $this->signature($time),
            'apiname' => 'Open_printLabelMsg',


            'sn' => '960283266',
            'content'=>$content,
            'times'=>1//打印次数
        );

        $client = new HttpClient('api.feieyun.cn','80');
        if(!$client->post('/Api/Open/',$msgInfo)){
            echo 'error';
        }else{
            $result = $client->getContent();
            dump($result);
        }exit();

        foreach ($glist['goods'] as $key => $value) {
//            $content .= '<TEXT x="9" y="10" font="12" w="1" h="2" r="0">'.$glist['z_number'].$i.'/'.$num.'</TEXT>';
//            $content .= '<TEXT x="9" y="180" font="12" w="1" h="1" r="0">'.$glist['name'].'</TEXT>';//40mm宽度标签纸一行占用26个字符，50mm宽度标签纸请改成32个字符
//            $content .= '<TEXT x="9" y="180" font="12" w="1" h="1" r="0">'.$glist['tel'].'</TEXT>';//40mm宽度标签纸一行占用26个字符，50mm宽度标签纸请改成32个字符
//            $content .= '<TEXT x="80" y="80" font="12" w="2" h="2" r="0">'.$value["title"].'</TEXT>';
//            $content .= '<TEXT x="80" y="80" font="12" w="2" h="2" r="0">'.$value["price"].'</TEXT>';
//            $content .= '<TEXT x="80" y="80" font="12" w="2" h="2" r="0">'.$value["num"].'</TEXT>';
//            $i+=1;
//             printLabelMsg(XXXXXXXXX,$content,1);//打开注释调用标签打印接口打印
            $time = time();         //请求时间
            $msgInfo = array(
                'user' => 'happygomall@163.com',
                'stime' => $time,
                'sig' => $this->signature($time),
                'apiname' => 'Open_printLabelMsg',


                'sn' => '960283266',
                'content'=>$content,
                'times'=>1//打印次数
            );

            $client = new HttpClient('api.feieyun.cn','80');
            if(!$client->post('/Api/Open/',$msgInfo)){
                echo 'error';
            }else{
                $result = $client->getContent();
                dump($result);
            }
        }
        exit();
//        $content = '';
//        // 编号
//        $print_number = time();
//        //$content .= "<CB>#P{$print_number}#</CB>";
//        //商家名称
//        $print_config['store_name'] = '小毛商户';
//        $pay_time_str =date('Y-m-d H:i:s');
//        $order['order_no'] = time();
//        $order['amount'] = 100;
//
//        $content .= "<C>{$print_config['store_name']}</C>";
//        $content .= "********************************";
//        $content .= "<BOLD>取单号：P{$print_number}</BOLD><BR>";
//        $content .= "支付时间: {$pay_time_str}<BR>";
//        $content .= "支付结果: 成功<BR>";
//        $content .= "--------------------------------<BR>";
//
//        if (!empty($order['remark'])) {
//            $content .= "备注：{$order['remark']}<BR>";
//            $content .= "--------------------------------<BR>";
//        }
//
//        $content .= "订单号:<BR>{$order['order_no']}<BR>";
//        $content .= "<BR><C>支付金额(元)</C>";
//        $content .= "<CB>{$order['amount']}</CB>";
//        $content .= "<C><BC128_B>{$order['order_no']}</BC128_B></C>";
//        $content .= "<CB>-- 完 --</CB>";

        exit();




        $content = '';
        // 编号
        $print_number = time();
        //$content .= "<CB>#P{$print_number}#</CB>";
        //商家名称
        $print_config['store_name'] = '小毛商户';
        $pay_time_str =date('Y-m-d H:i:s');
        $order['order_no'] = time();
        $order['amount'] = 100;

        $content .= "<C>{$print_config['store_name']}</C>";
        $content .= "********************************";
        $content .= "<BOLD>取单号：P{$print_number}</BOLD><BR>";
        $content .= "支付时间: {$pay_time_str}<BR>";
        $content .= "支付结果: 成功<BR>";
        $content .= "--------------------------------<BR>";

        if (!empty($order['remark'])) {
            $content .= "备注：{$order['remark']}<BR>";
            $content .= "--------------------------------<BR>";
        }

        $content .= "订单号:<BR>{$order['order_no']}<BR>";
        $content .= "<BR><C>支付金额(元)</C>";
        $content .= "<CB>{$order['amount']}</CB>";
        $content .= "<C><BC128_B>{$order['order_no']}</BC128_B></C>";
        $content .= "<CB>-- 完 --</CB>";
        $msgInfo['contents'] = $content;
        $msgInfo['times'] = 1;
//        dump($msgInfo);exit();
        $client = new HttpClient('api.feieyun.cn','80');
        if(!$client->post('/Api/Open/',$msgInfo)){
            echo 'error';
        }else{
            $result = $client->getContent();
            $this->success('ok',json_decode($result,true));
        }
    }

    public function fee2(){

        $time = time();         //请求时间
        //$printerConten => 打印机编号sn(必填) # 打印机识别码key(必填) # 备注名称(选填) # 流量卡号码(选填)，多台打印机请换行（\n）添加新打印机信息，每次最多100台。
        //打开注释可测试
        //$printerContent = "sn1#key1#remark1#carnum1\nsn2#key2#remark2#carnum2";
        $msgInfo = array(
            'user'=>'happygomall@163.com',
            'stime'=>$time,
            'sig'=>$this->signature($time),
            'apiname'=>'Open_printerAddlist',
            'printerContent'=>"960283266#RKxbtv9c"
        );
        $client = new HttpClient('api.feieyun.cn','80');
        if(!$client->post('/Api/Open/',$msgInfo)){
            echo 'error';
        }else{
            $result = $client->getContent();
            $this->success('ok',json_decode($result,true));
        }
    }

    public function ceshi1688(){
        $config = get_addon_config('wanlshop');
        dump($config);exit();
        $key = input('keyword');
        $page = input('page',1);
        $cache = input('cache');
        $pageSize = input('pageSize',50);
        $accessToken = 'c28cc341-d5cc-414e-93eb-316c4188a2dc';
        $codeAar = array(
            'access_token'=>$accessToken,
            'pageNum' => $page,
            'pageSize' => $pageSize,
        );
        if($key){
            $codeAar['keyword'] = $key;
        }
        if(cache($cache)){
//            echo '22';
            $offerIds = json_decode(cache($cache),true);
        }else{
            $apiInfo = 'param2/1/com.alibaba.fenxiao/jxhy.product.getPageList/';
            $sdk = new AlibabaSignatureGenerator($apiInfo,$accessToken);
            $res = $sdk->sendData($codeAar);
            $result = array("currentPage"=> $res['result']['pageInfo']['currentPage'],"totalRecords"=> $res['result']['pageInfo']['totalRecords'],"pageSize"=> $res['result']['pageInfo']['pageSize'],"rows" => $res['result']['result']);
            $offerIds = [];
            foreach ($result['rows'] as $key => $value) {
                $offerIds[$key] = $value['itemId'];
            }
            cache('nvzhuang', json_encode($offerIds,true));
        }
        $apiInfo = 'param2/2/com.alibaba.fenxiao/alibaba.pifatuan.product.detail.list/';

        $sdk = new AlibabaSignatureGenerator($apiInfo,$accessToken);
        $codeAar = array(
            'access_token'=>$accessToken,
            'offerIds' => json_encode($offerIds,true),
        );
        $goodsDataAlbaba = cache('goods-'.$cache);
        if($goodsDataAlbaba){
            $goodsDataAlbaba = json_decode(cache('goods-'.$cache),true);

        }else{
            $res = $sdk->sendData($codeAar);
            $goodsDataAlbaba = $res['result']['result'];
            cache('goods-'.$cache,json_encode($goodsDataAlbaba,true));
        }
        if(!empty($goodsDataAlbaba)){
            $goodsModel = new \app\index\model\wanlshop\Goods;
            $spuModel = new GoodsSpu();
            $skuModel =  new GoodsSku();
            foreach ($goodsDataAlbaba as $key => $value) {
                $value = $value['productInfo'];
                if($value['status'] == 'published' || $value['status'] == 'approved'){
                    $goodsData['image']  = 'https://cbu01.alicdn.com/'.$value['image']['images'][0];
                    foreach ($value['image']['images'] as $kk=>&$vv){
                        $vv  = 'https://cbu01.alicdn.com/'.$vv;
                    }
                    $goodsData['images'] = implode(',',$value['image']['images']);
                    $goodsData['description'] = $value['subject'];
                    $goodsData['shop_id'] = 1;
                    $goodsData['yaun_price'] = $value['skuInfos'][0]['pifaPrice'];
                    $goodsData['price'] = $value['skuInfos'][0]['pifaPrice'] + $value['skuInfos'][0]['pifaPrice']*'0.6';
                    $goodsData['content'] = $value['description']??'';
                    $goodsData['freight_id'] = 25;
                    if(count($value['attributes']) > 1){
                        $goodsData['specs'] = 'single';
                    }else{
                        $goodsData['specs'] = 'multi';
                    }
//                    $goodsData['price'] = $value['skuInfos'][0]['consignPrice'];
                    Db::startTrans();
                    try {
                        $goodsData['sales'] = $value['bookedCount']??0;

//                        $goodsModel->create($goodsData);

                        foreach ($value['skuInfos'] as $kk=>$vv){
                            foreach ($vv['attributes']  as $kkk=>$vvv){
                                $spu['name'] = $vv['attributeName'];
                                $spu['item'] = $vv['attributeName'];
                                $spu['name'] = $vv['attributeName'];
                            }

                            dump($vv);
                        }
//                        dump($goodsData);
                        Db::commit();
                    }catch (Exception $e){
                        Db::rollback();
                    }


                }

            }
        }
    exit();



        $access_token = 'c28cc341-d5cc-414e-93eb-316c4188a2dc';
//        $apiInfo = 'param2/1/com.alibaba.fenxiao/jxhy.product.getPageList/';
        $codeAar = array(
            'keyword' => '内衣',
        );
        $apiInfo = 'param2/1/com.alibaba.product/alibaba.category.searchByKeyword/';
        $sdk = new AlibabaSignatureGenerator($apiInfo,$access_token);
        $res = $sdk->sendData($codeAar);
        dump($res);exit();
        $url = 'https://gw.open.1688.com/openapi/';//1688开放平台使用gw.open.1688.com域名
        $appKey = '1402148';
        $appSecret ='heYQz0AdJ9';
        $apiInfo = 'param2/1/com.alibaba.fenxiao/jxhy.product.getPageList/'.$appKey;//此处请用具体api进行替换
        //配置参数，请用apiInfo对应的api参数进行替换

        $code_arr = array(
            'access_token'=>$access_token,
            'pageNum' => '1',
            'pageSize' => '10',
        );
        $aliParams = array();
        foreach ($code_arr as $key => $val) {
            $aliParams[] = $key . $val;
        }
        sort($aliParams);
        $sign_str = join('', $aliParams);
        $sign_str = $apiInfo . $sign_str;
        $_aop_signature = strtoupper(bin2hex(hash_hmac("sha1", $sign_str, $appSecret, true)));
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url.$apiInfo);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);

        curl_setopt($ch, CURLOPT_FAILONERROR, false);

        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/x-www-form-urlencoded']);
        curl_setopt($ch, CURLOPT_POSTFIELDS, 'pageNum=1&pageSize=10&access_token='.$access_token.'&_aop_signature='.$_aop_signature);
        curl_setopt($ch, CURLOPT_POST, 1);

//        echo "Start to run...\n";
        $output = curl_exec($ch);
        curl_close($ch);
        $arr = json_decode($output, true);
        $this->success('',$arr['result']['result']);
    }


    public function da(){
        $printerId = "862092072557709";
        $linkUrl = 'http://link.cainiao.com/gateway/link.do';
//        $printData['templateUrl'] = 'http://cloudprint.cainiao.com/template/standard/401';
        $printData = input('');
//        $printData['printData']['templateUrl'] = 'http://cloudprint.cainiao.com/template/standard/401';
//        $content = ["printerId" => $printerId,'sharedCode'=>'6068','userId'=>'1234','printData'=>$printData['printData']];     // 如果接口配置为json格式，这儿内容就是json，否则是xml格式
//        var_dump($printData);exit();
        $content = $printData;
        $appSecret = 'KqrQx1T6q57MqSM9Bu5yQTYg95uWFm14';    // APPKEY对应的秘钥
        $cpCode = 'cc2ead9221172c175d590ef7e3140638';     //调用方的CPCODE
        $msgType = 'CLOUDPRINT_PRINTER_PRINT';    //调用的API名
        $digest = base64_encode(md5(json_encode($printData).$appSecret, true));     //生成签名
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $linkUrl);

// For debugging

        curl_setopt($ch, CURLOPT_VERBOSE, 1);

        curl_setopt($ch, CURLOPT_FAILONERROR, false);

        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/x-www-form-urlencoded']);

        $post_data = 'msg_type='.$msgType
//            .'&to_code='.$toCode
            .'&logistics_interface='.urlencode(json_encode($content))
            .'&data_digest='.urlencode($digest)
            .'&logistic_provider_id='.urlencode($cpCode);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data );
        curl_setopt($ch, CURLOPT_POST, 1);

//        echo "Start to run...\n";
        $output = curl_exec($ch);
        dump($output);exit();
        curl_close($ch);
        var_dump(json_encode($output));exit();
//        echo "Finished, result data is: \n".json_encode($output);

    }
    /**
     * 将数组转换为XML
     * @param array $data 要转换的数组
     * @param SimpleXMLElement $xmlData XML数据对象
     */
   public function arrayToXml($data, &$xmlData) {
        foreach ($data as $key => $value) {
            if (is_array($value)) {
                if (is_numeric($key)) {
                    $key = 'item'.$key; // 处理数字键名
                }
                $subNode = $xmlData->addChild($key);
              $this->arrayToXml($value, $subNode);
            } else {
                $xmlData->addChild("$key", htmlspecialchars("$value"));
            }
        }
    }

    public function test(){

        $file = input('file');
        $to = 'russian';
        $arr = [];
//        dump($file);exit();
        $langFile = '/www/wwwroot/ch.jiamansi.shop/application/index/lang/en/wanlshop/'.$file.'.php';

// 1. 备份源文件（安全防护）
//        $backupFile = $langFile . '.' . date('YmdHis') . '.bak';
//        if (!copy($langFile, $backupFile)) {
//            throw new Exception("文件备份失败，请检查权限或路径");
//        }
// 2. 获取并翻译语言包
$langArray = include $langFile;
foreach ($langArray as $key => $value) {
    $translation = (new \app\common\library\Youdao)->send($value ?: $key, $to);
    $arr[$key] = $translation['translation'][0] ?? '';
}

dump($arr);
// 3. 生成符合原格式的PHP文件内容
$content = "<?php\n\nreturn [\n";
foreach ($arr as $key => $value) {
    // 转义特殊字符防止语法错误
    $escapedKey = str_replace(['\'', '\\'], ['\\\'', '\\\\'], $key);
    $escapedValue = str_replace(['\'', '\\'], ['\\\'', '\\\\'], $value);

    // 保留原文件格式：每行一个键值对
    $content .= "    '{$escapedKey}' => '{$escapedValue}',\n";
}
    $content .= "];"; [2,3];
    file_put_contents($langFile, $content, LOCK_EX);
// 4. 安全写入（锁定文件防并发写入）
//if (file_put_contents($langFile, $content, LOCK_EX) === false) {
//    // 失败时恢复备份
//    copy($backupFile, $langFile);
//    throw new Exception("文件写入失败，已恢复备份");
//};

exit();






//        $key = input('');
//        $arr = json_decode($key,true);
//        dump($key);exit();
        $to  = 'russian';
        $arr = [];

        // 定义语言包文件路径（根据实际路径修改）
        $langFile = '/www/wwwroot/shop.hncq56.com/application/index/lang/en.php';

// 包含文件并获取返回的数组
        $langArray = include $langFile;
            // 遍历数组
            foreach ($langArray as $key => $value) {
                if($value){
                    $arr[$key] =  (new \app\common\library\Youdao)->send($value,$to)['translation'][0];
                }else{
                    $arr[$key] =  (new \app\common\library\Youdao)->send($key,$to)['translation'][0];
                }
            }
//            $this->success('ok',$arr);
       var_dump($arr);exit();

        foreach ($key as $k=>$v){

//            dump($v);
        }
        dump($arr);

        exit();
        $data = (new \app\common\library\Youdao)->send($key,$to);
    }

    public function ceshi(){
//        $da = cache('cate');
        $key = input('key');
        $to  = input('to');
        $data = (new \app\common\library\Youdao)->send($key,$to);
        $this->success('ok',$data['translation'][0]);

        $redis = Common::redis();
        $redisKey = 'goods:'.$to.'-'.$key;
        $text = $redis->get($redisKey);
        dump($text);
        if(!$text){
            $data = (new \app\common\library\Youdao)->send($key,$to);
            $redis->set($redisKey, $data['translation'][0]);
            dump($data['translation'][0]);exit();
        }
exit();
//        $data['q'] = '超级豆豆鞋';
//        $data['from'] ='auto';
//        $data['to'] = 'mn';
//        $data['appKey'] = '729525389fe24d6e';
//        $data['salt'] = time();
//        $data['signType'] = 'v3';
//        $data['curtime'] = time();
//        $data['sign'] = calculateSignature(
//            $data['appKey'],
//            $data['q'],
//            $data['salt'],  // 需与上方一致
//            $data['curtime'],
//            'a0V5XRCD5zJcoFJwrmZxoafrybnxTIvj'
//        );
//        $url = 'https://openapi.youdao.com/api';
//        $data =  httpGetRequest($url,$data);
//        dump($data);exit();
        dump(json_decode($data['body'],true));exit();
//        dump($da);exit();
//        $model       = new Category2();
//        $data = $model->select();
//        foreach ($data as $k=>$v){
//            if($v['image']){
//                if(strpos($v['image'], 'http://') !== false){
//                    $imageUrl = $v['image'];
//                    $fileExt = pathinfo(parse_url($imageUrl, PHP_URL_PATH), PATHINFO_EXTENSION) ?: 'jpg';
//                    $safeName = $v['id']. "_$k.$fileExt".'.jpg';
//                    $savePath = './uploads/wanlshop_category/' . $safeName;
//                    // 执行下载
//                    downloadImage($imageUrl, $savePath);
//                    $v->image = trim($savePath,'.');
//                    $r = $v->save();
////               dump($r);exit();
//                    echo "下载成功: {$v['name']} -> $savePath\n";
//                }
//            }
//        }
//        foreach ($da as $k=>$v){
//            $model       = new Category2();
//            $model->type = 'goods';
//            $model->name = $v['main_name'];
//            $model->save();
//            $cateInfo = $model->where(['name'=>$v['main_name']])->find();
//            if($cateInfo){
//                foreach ($v['data'] as $kk=>$vv){
//                    $model = new Category2();
//                    $model->type = 'goods';
//                    $model->name = $vv['next_name'];
//                    $model->pid  = $cateInfo->id;
//                    $model->save();
//                    $ids = $model->id;
//                    foreach ($vv['info'] as $kkk=>$vvv){
//                        $model = new Category2();
//                        $model->type = 'goods';
//                        $model->name = $vvv['son_name'];
//                        $model->pid  = $ids;
//                        $model->image = $vvv['imgurl'];
//                        $model->save();
//                      $imageUrl = $vvv['imgurl'];
//                      dump($imageUrl);
//                    $fileExt = pathinfo(parse_url($imageUrl, PHP_URL_PATH), PATHINFO_EXTENSION) ?: 'jpg';
//                    $safeName = $vvv['son_name']. "_$kkk.$fileExt".'.jpg';
//                    $savePath = './uploads/wanlshop_category_two/' . $safeName;
////                    // 执行下载
//                    downloadImage($imageUrl, $savePath);
//                        echo "下载成功: {$vvv['son_name']} -> $savePath\n";
//                    }
//                }
//            }
//        }
//        dump($da);
        exit();
        if($body){
            foreach ($body['general_classify'] as $k=>$v){

            }
        }
        $url = 'http://v2.api.haodanku.com/super_classify?apikey=B8690A7B0003';
        $data =  httpGetRequest($url);
        if($data['status'] == 200){
            $body = json_decode($data['body'],true);

            dump($body);exit();
        }

//        $sfd = new SfdPay();
//        $url  = 'http://gos-erp.yundasys.com:45120/v1/logistics/query/mn';
//        $params['shipId'] = '464422732138614';
//        $params['account'] = 'nm20250612';
//        $pwd = '86eb5fee5cfc96abc32d4c1b4bdb601b';
//        $params['sign']    = md5($params['account'].$pwd.$params['shipId']);
//
//      $res =  $sfd->curlPost($url,$params);
//        dump(json_decode($res,true));exit();
//        return curl_exec($ch);
//
//        dump(get_addon_config('wanlshop')['h5']['domain']);
//        exit();
//        $shopInfo = db('wanlshop_shop')->where(['id'=>24])->find();
//        $a = getMargin($shopInfo['id'],$shopInfo['keyvalue']);
//        dump($a);exit();
       $baishi = new Baishi();
       dump($baishi->send('81872941695'));exit();
        $url = "http://edi-v5.800best.com/gateway/v5api/kyapi";//对应的地址
        $partnerID = "69212";//根据实际partnerID
        $partnerKey = "e1vxnqckwr57";//根据实际partnerKey
        $format = "JSON";//如果是JSON的数据格式，填JSON
        include_once  ROOT_PATH."kyapi/Client.php";
        include_once  ROOT_PATH."kyapi/kyTraceQuery/request/KyTraceQueryReq.php";
        $client = new Client($url, $partnerID, $partnerKey, $format);
        $kyTraceQueryReq = new KyTraceQueryReq();
        $kyTraceQueryReq->setLogisticCompanyID("BESTQJT");
        $kyTraceQueryReq->setLogisticID("81872941695");
        $codes = Array("81872941695");
        $kyTraceQueryReq->setCodes($codes);

        $kyTraceQueryRsp = $client->executed($kyTraceQueryReq);
        dump(json_decode( $kyTraceQueryRsp,true));
        exit();


        $ip2region = new Ip2Region();
        $info = $ip2region->memorySearch(get_client_ip());
        dump($info);exit();
        $sfd = new SfdPay();
        //odQMD7g6dY0YLAw60O8oUx1lROzE
//        	        dump($data);exit();
        $sfdParams['party_order_number'] = '4850892850100132';
        $sfdParams['total_amount']       = '100';
        $sfdParams['is_minipg']          = 1;
        $sfdParams['appid']              = 'wx299491d9ccba75e2';
        $sfdParams['buyer_id']           = 'odQMD7g6dY0YLAw60O8oUx1lROzE';
        $sfdParams['client_ip']          = get_client_ip();
        $sfdParams['subject']            = '测试';
        $sfdParams['notify_url']         = 'https://shop.hncq56.com/api/wanlshop/callback/notify/type/wechat';
        $sfdParams['timestamp']          = time();
        $sfdParams['business_code']      = config('site.sfd_business_code');
        $sfdParams['mch_num']            = config('site.sfd_mch_num');
        $sfdParams['sign']  = $sfd->sign($sfdParams);
        dump($sfdParams);
        $res =  $sfd->curlPost(config('site.sfd_url').'/pay_gate/wechat', $sfdParams);
        dump($res);exit();
//        $params['return_url'] = 'https://shop.hncq56.com/web';
//        $params['notify_url'] = 'https://shop.hncq56.com/api/wanlshop/callback/notify/type/wechat';
//        $params['party_order_number'] = time();
//        $params['total_amount'] = '0.01';
//        $params['client_ip'] = get_client_ip();
//        $params['subject'] = '购买商品';
//        $params['payment'] = 1;
//        $params['business_code'] = '80000935';
//        $params['mch_num'] = '92625085';
//        $params['timestamp'] = time();
//        $params['sign']  = $this->sign($params);
//        $res =  $this->curlPost('https://api.kfim.cn/pay_gate/app_pay', $params);
//        $this->success('',json_decode($res,true));
        $shopSortModel = new \app\api\model\wanlshop\Shop();
        $shopId = 3;
        $shopInfo = $shopSortModel->where(['id'=>$shopId])->whereNotNull('keyvalue')->field('id,keyvalue')->find();
        $margin = 0;
        if($shopInfo){
            //获取用户是第几次缴纳保证金
            $arr = [];
            $orderModel = new ShopMarginOrder();
            $orderCount = $orderModel->where(['shop_id'=>$shopId,'status'=>1])->count();
            $marginAll = (new Pay())->where(['pay_state'=>1])->sum('actual_payment');
            $keyvalue = json_decode($shopInfo['keyvalue'],true);
            if(!$orderCount){
                $margin = $keyvalue[0];
            }else{
                unset($keyvalue[0]);
                //根据营业额倒序，获取最高营业额的保证金
                krsort($keyvalue);
               foreach ($keyvalue as $k=>$v){
                   if($marginAll > $k){
                       $margin = $v;
                        break;
                   }
               }
            }
        }
        dump($margin);
        exit();
    }

    /**
     * POST请求
     * @param {Object} $post_url
     * @param {Object} $post_data
     */
    public function curlPost($post_url, $post_data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $post_url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        return curl_exec($ch);
    }

    /**
     * 私钥签名
     *
     * @param  array  $arr  参数
     * @return string
     */
   public function sign($arr)
    {
        unset($arr['sign']);
        $str = $this->signQueryString($arr); // 参数处理
        $pk = '-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDFEut5FobFaXY9
KZoioiTiJOp1ADNRCHFzhmirCg0MnvIq8cNNbNtSBHw2ROiZDAkcltZsANMoCMAK
NbJS3rB2SWc1aA6kwv60OzqkvqBDQzb4UnpMxdWsG4e356SRvoNOm6AhVz/7Bo+2
/vCIKT8OFG2u2sWBcFaE024nfr1sMM4uFO3GsZtJxlZNcBhyGnVkb7qFkdiO2KvV
YT42nff12QrpJgUUgbAp4SDMtBF/zYrm2ULsjRq/mLoocYNw1b9CPOTMbu4q1GYQ
cPSX9yEHq8FklfHd4STdLpMOwLecWNsCHP70TlBfe/ZR6Ndc6kvmHp0tHa1tGRrB
sBNYBZnlAgMBAAECggEAaDNkxhWfFOp6VkSU9xL8pYYXYd3FRGdOdWLwHN+nnrC8
IvDJ7zpLjMZKVveAdMvkVXV70odtHpHh2IQj0aVlcGXHaHmopH1l5y4aB9mzK11y
x0H04HsKS4IS9K5KWbV+ACZROM/FSJlji8Kos5X7fRpYFEggfhxD4t9YMxHUXktQ
lJyfoJlMtk9QGulmXaMxhl2bBepADraVIJq9MLBkmsc3U9Eq27hHKAgaOw88AmG/
bEV7SAqz7VnaP0yhHSIl/KZ7VjHf7+8wPe4uNYL+p9Qm6lBv8rdp3Z/8T27zo/RK
vBgLtRkzFonwTcfed79CUJ2DzjIIxnOJ6VCfgd0ZUQKBgQD+lTmHg95kPfBV3UYw
ckHE5YAyjfGjugPnV8IIHmRfFtsgV4ZrJabJXRH/cosKjAr/YyURWsV9R7mKZG0b
Pant7YzwhhGJAMl23VIjLgmZapemjMCPPmtj6D2OUhx9I/pElKtpElKGjRD4BWQh
qAkYpadh42drZxIeSxUwzPVemwKBgQDGK774O9gcXVZabxa33jS3orpyhE78WjRl
SJQ0gMtNq4Pxo3+EzCsrl6cDThe3mI181583O2M7ECoSWp4CiBOXp/zvPwb472uJ
ARKcySlmFPnBMmHptOOesxaX0PpgVUNwoQTmBDn2U9+Fd5Kn8Es+Tgfo9gohkrAD
2ECSNJAxfwKBgQDAbwe3WYRG/VKndMTTZeo07M1EaWrXuYmt2vX9sQtpnRsxjTc7
0pAJ8WHjVy+mX0kI1mZ0gcp58jdbVqHqT2gdQsygGpcymfeu84hcszXqU1oiOI5t
OF9we2HcLFEAfqt0H3SZzZG3xvWmpFyV3DBUAxNMuNm5o4VchKCV7LckNQKBgGF2
km2zwQ3yOc4wZJP5jSPjvJ8lw1MJakuF7p4D2flRKYtmRgkiAPlnlJRji/aX6L5F
reCULLGXuZldR+km07v6usNP1DYKSnEPPgAuT1YNauhBxzYR6QDcQ3hXJ0zJoml6
R9Z4rakghwY1UMOXwunZprpEh6cLZdX+PYOqpmAxAoGAJcgRoon4tulNjyBm10f5
T63WlT7RGW3bykA3wG+FiwMinJhn36Pm1OQfWoQgn8t4Fqmph1pd0ECL4iekLtrf
gqeruqKBfq8HpxfrUnmNqCx9XPrT1JoyPiRbihEWtptVNYGCsaVYeZb8CrljTLFo
UTCjJIo0e+M+72dQgZc8asE=
-----END PRIVATE KEY-----';
        $pi_key = openssl_pkey_get_private($pk);
        openssl_sign($str, $signature, $pi_key,OPENSSL_ALGO_SHA1);
        unset($pi_key);
        return base64_encode($signature);
    }

    /**
     * 参数处理
     *
     * @param  array  $params
     * @return string
     */
   public function signQueryString($params)
    {
        ksort($params);
        $qb_str = '';
        foreach ($params as $key => $val) {
            if (!empty($val)) {
                $qb_str .= $key . '=' . $val . '&';
            }
        }
        return rtrim($qb_str, '&');
    }
}
